<?php

namespace App\Jobs;

use Illuminate\Support\Facades\Mail;
use App\Models\MailConfig;
use Illuminate\Mail\MailServiceProvider;
use Illuminate\Support\Facades\Log;

class MailJob extends Job
{
    public $hallID;
    public $to;
    public $title;
    public $content;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($hallID, $to, $title, $content)
    {
        $this->hallID = $hallID;
        $this->to = $to;
        $this->title = $title;
        $this->content = $content;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $mc = MailConfig::where(['hall_id' => $this->hallID])->first();
        if (empty($mc)) {
            Log::error("Can't find Mail Config! HallID：" . $this->hallID);
            return;
        }
        $default = config('mail');
        $default['host'] = $mc['host'];
        $default['port'] = $mc['port'];
        $default['from']['address'] = $mc['from_address'];
        $default['from']['name'] = $mc['from_name'];
        $default['encryption'] = null;
        if (!empty($mc['encryption'])) {
            $default['encryption'] = $mc['encryption'] == 1 ? 'tls' : 'ssl';
        }
        $default['username'] = $mc['username'];
        $default['password'] = $mc['password'];
        config(['mail' => $default]);
        // 使用新的配置强行重刷
        (new MailServiceProvider(app()))->register();

        Mail::raw($this->content, function ($message) {
            $message->to($this->to)->subject($this->title);
        });
    }
}
